﻿using _537AppStore_API.Model;
using _537AppStore_API.Data;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Microsoft.AspNetCore.Components;

namespace _537AppStore_API.Controller
{
    /// <summary>
    /// 应用程序控制器
    /// 具有获取、添加、删除等功能
    /// 
    /// </summary>
    [Microsoft.AspNetCore.Mvc.Route("api/[controller]")]
    [ApiController]
    public class ApplicationController : ControllerBase
    {

        public readonly AppDbContext _db;
        public ApplicationController(AppDbContext db)
        {
            _db = db;
        }
        /// <summary>
        /// 获取所有应用程序
        /// </summary>
        [HttpGet]
        public async Task<ActionResult<IEnumerable<Application>>> GetApplications()
        {
            return await _db.Application.ToListAsync();
        }

        /// <summary>
        /// 根据 name 获取单个应用程序
        /// </summary>
        [HttpGet("{Name}")]
        public async Task<ActionResult<Application>> GetApplication(string Name)
        {
            var application = await _db.Application.FindAsync(Name);
            if (application == null)
            {
                return NotFound(); // 404 未找到
            }
            return application;
        }

        /// <summary>
        /// 添加新应用程序
        /// </summary>
        [HttpPost]
        public async Task<ActionResult<Application>> PostApplication(Application application)
        {
            application.id = Guid.NewGuid(); // 自动生成 ID
            application.LastUpdated = DateTime.Now; // 自动设置更新时间
            _db.Application.Add(application);
            await _db.SaveChangesAsync();

            // 返回 201 Created 及新创建的资源地址
            return CreatedAtAction(nameof(GetApplication), new { application.id }, application);
        }

        /// <summary>
        /// 更新应用程序
        /// </summary>
        [HttpPut("{id}")]
        public async Task<IActionResult> PutApplication(Guid id, Application application)
        {
            if (id != application.id)
            {
                return BadRequest(); // ID 不匹配
            }
            _db.Entry(application).State = EntityState.Modified;
            application.LastUpdated = DateTime.Now; // 更新时间戳

            try
            {
                await _db.SaveChangesAsync();
            }
            catch (DbUpdateConcurrencyException)
            {
                if (!ApplicationExists(id))
                {
                    return NotFound();
                }
                throw;
            }

            return NoContent(); // 204 无内容
        }

        /// <summary>
        /// 删除应用程序
        /// </summary>
        [HttpDelete("{id}")]
        public async Task<IActionResult> DeleteApplication(Guid id)
        {
            var application = await _db.Application.FindAsync(id);
            if (application == null)
            {
                return NotFound();
            }

            _db.Application.Remove(application);
            await _db.SaveChangesAsync();

            return NoContent();
        }

        // 辅助方法：检查应用是否存在
        private bool ApplicationExists(Guid id)
        {
            return _db.Application.Any(e => e.id == id);
        }
    }
}
